import axios from "axios";

import { ElMessage, ElMessageBox } from 'element-plus'

import { showLoading, hideLoading } from '@/utils/loading'
var baseUrl = 'https://www.sannongpeixun.com/tm-openapi'
const instance = axios.create({
  baseURL:baseUrl,
  timeout: 5000,
});

instance.interceptors.request.use(config => {
  // 请求拦截进来调用显示loading效果
  // showLoading()
 config.data = config.params || {}
 config.headers['M-SESSION'] = localStorage.getItem('userUuid') || ''
 // config.headers['Content-Type'] = 'application/json'
  // 断网提示
  if (!navigator.onLine) {
    ElMessageBox.alert(
      '您的网络故障，请检查!', 
      '温馨提示',
      {
        confirmButtonText: '好的',
        type: 'warning'
      }
    )
  }
 
  // 判断是否存在token，如果存在将每个页面header都添加token
  // if (getToken()) {
  //   config.headers.Authorization = getToken()
  // }
  return config
}, error => {
  console.log('请求拦截error', error)
  // 对请求错误做些什么
  return Promise.reject(error)
})

instance.interceptors.response.use(
  
  (response) => {
    setTimeout(() => {
      hideLoading()
    }, 200)
    const { data, config } = response;
    const { code, msg } = data;
    // 操作正常Code数组
    const codeVerificationArray = [...[1]];
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      return data;
    } else {
      return data;
      // return Promise.reject(
      //   "请求异常拦截:" + JSON.stringify({ url: config.url, code, msg }) ||
      //     "Error"
      // );
    }
  },
  (error) => {
    if (error.response && error.response.data) {
      return Promise.reject(error);
    } else {
      let { message } = error;
      if (message === "Network Error") {
        message = "后端接口连接异常";
      }
      if (message.includes("timeout")) {
        message = "后端接口请求超时";
      }
      if (message.includes("Request failed with status code")) {
        const code = message.substr(message.length - 3);
        message = "后端接口" + code + "异常";
      }
      return Promise.reject(error);
    }
  }
);

export default instance;
